﻿using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Brianhdk.Utils.VisualStudio.AssemblyInfoDialog
{
    internal class RetrieveAssemblyFilePathFromProjectFile : IAssemblyFilePathStrategy
    {
        private readonly FileInfo _projectFile;

        public RetrieveAssemblyFilePathFromProjectFile(string projectFile)
        {
            _projectFile = new FileInfo(projectFile);
        }

        public string GetFilePath()
        {
            var projectFileXml = XDocument.Load(_projectFile.FullName);

            XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";

            var assemblyName =
                projectFileXml.Root
                    .Element(msbuild + "PropertyGroup")
                    .Element(msbuild + "AssemblyName")
                    .Value;

            var outputPaths =
                projectFileXml.Root
                    .Elements(msbuild + "PropertyGroup")
                    .Elements(msbuild + "OutputPath")
                    .Select(x => x.Value);

            return 
                outputPaths
                    .SelectMany(x => new[]
                    {
                        Path.Combine(_projectFile.DirectoryName, x, assemblyName + ".dll"),
                        Path.Combine(_projectFile.DirectoryName, x, assemblyName + ".exe")
                    })
                    .FirstOrDefault(File.Exists);
        }
    }
}